<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { NButton, NSpace, NPopconfirm, NTag, NDrawer, NDescriptions, NDescriptionsItem, NCard, NStatistic, NGrid, NGridItem } from 'naive-ui';
import { fetchHistoryFileRecords, fetchHistoryFileRecordDetail, previewHistoryFileData, downloadHistoryFile, fetchHistoryFileStatistics } from '@/service/api';
import { useLoading } from '@sa/hooks';
import { $t } from '@/locales';

defineOptions({
  name: 'FileCollectionHistory'
});

const { loading, startLoading, endLoading } = useLoading(false);
const { loading: detailLoading, startLoading: startDetailLoading, endLoading: endDetailLoading } = useLoading(false);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  fileName: '',
  fileType: '',
  status: '',
  ruleId: undefined as number | undefined,
  startTime: null as string | null,
  endTime: null as string | null
});

// 表格数据
const tableData = ref<any[]>([]);
const total = ref(0);

// 统计数据
const statistics = ref<Record<string, any>>({});

// 详情抽屉
const detailDrawerVisible = ref(false);
const currentRecord = ref<any>(null);

// 预览抽屉
const previewDrawerVisible = ref(false);
const previewData = ref<any>(null);

// 文件类型选项
const fileTypeOptions = [
  { label: '全部', value: '' },
  { label: 'CSV', value: 'CSV' },
  { label: 'Excel', value: 'EXCEL' },
  { label: 'XML', value: 'XML' },
  { label: 'JSON', value: 'JSON' },
  { label: 'SQL', value: 'SQL' }
];

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '待处理', value: 'PENDING' },
  { label: '解析中', value: 'PARSING' },
  { label: '成功', value: 'SUCCESS' },
  { label: '失败', value: 'FAILED' }
];

// 表格列定义
const columns = [
  {
    title: '文件名',
    key: 'fileName',
    width: 200,
    ellipsis: { tooltip: true }
  },
  {
    title: '文件类型',
    key: 'fileType',
    width: 100,
    render: (row: any) => {
      return h(NTag, { type: 'info' }, { default: () => row.fileType });
    }
  },
  {
    title: '文件大小',
    key: 'fileSize',
    width: 120,
    render: (row: any) => {
      return formatFileSize(row.fileSize);
    }
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    render: (row: any) => {
      const statusMap: Record<string, { type: any; label: string }> = {
        PENDING: { type: 'default', label: '待处理' },
        PARSING: { type: 'info', label: '解析中' },
        SUCCESS: { type: 'success', label: '成功' },
        FAILED: { type: 'error', label: '失败' }
      };
      const status = statusMap[row.status] || { type: 'default', label: row.status };
      return h(NTag, { type: status.type }, { default: () => status.label });
    }
  },
  {
    title: '解析记录数',
    key: 'parsedRecords',
    width: 120,
    align: 'right'
  },
  {
    title: '入库记录数',
    key: 'loadedRecords',
    width: 120,
    align: 'right'
  },
  {
    title: '采集时间',
    key: 'createTime',
    width: 180
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    fixed: 'right',
    render: (row: any) => {
      return h(
        NSpace,
        {},
        {
          default: () => [
            h(
              NButton,
              {
                size: 'small',
                onClick: () => handleViewDetail(row.id)
              },
              { default: () => '详情' }
            ),
            h(
              NButton,
              {
                size: 'small',
                onClick: () => handlePreview(row.id)
              },
              { default: () => '预览' }
            ),
            h(
              NButton,
              {
                size: 'small',
                onClick: () => handleDownload(row.id)
              },
              { default: () => '下载' }
            )
          ]
        }
      );
    }
  }
];

// 查询列表
async function getList() {
  startLoading();
  try {
    const { data } = await fetchHistoryFileRecords(queryParams);
    if (data) {
      tableData.value = data.rows || [];
      total.value = data.total || 0;
    }
  } finally {
    endLoading();
  }
}

// 查询统计
async function getStatistics() {
  try {
    const { data } = await fetchHistoryFileStatistics(queryParams);
    if (data) {
      statistics.value = data;
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
}

// 搜索
function handleSearch() {
  queryParams.pageNum = 1;
  getList();
  getStatistics();
}

// 重置
function handleReset() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    fileName: '',
    fileType: '',
    status: '',
    ruleId: undefined,
    startTime: null,
    endTime: null
  });
  getList();
  getStatistics();
}

// 查看详情
async function handleViewDetail(id: number) {
  startDetailLoading();
  try {
    const { data } = await fetchHistoryFileRecordDetail(id);
    if (data) {
      currentRecord.value = data;
      detailDrawerVisible.value = true;
    }
  } finally {
    endDetailLoading();
  }
}

// 预览数据
async function handlePreview(id: number) {
  startDetailLoading();
  try {
    const { data } = await previewHistoryFileData(id, 100);
    if (data) {
      previewData.value = data;
      previewDrawerVisible.value = true;
    }
  } finally {
    endDetailLoading();
  }
}

// 下载文件
async function handleDownload(id: number) {
  try {
    const { data } = await downloadHistoryFile(id);
    if (data) {
      window.open(data, '_blank');
    }
  } catch (error) {
    window.$message?.error('下载失败');
  }
}

// 格式化文件大小
function formatFileSize(bytes: number): string {
  if (!bytes) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
}

// 分页变化
function handlePageChange(page: number) {
  queryParams.pageNum = page;
  getList();
}

function handlePageSizeChange(pageSize: number) {
  queryParams.pageSize = pageSize;
  queryParams.pageNum = 1;
  getList();
}

onMounted(() => {
  getList();
  getStatistics();
});
</script>

<template>
  <div class="h-full flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <!-- 统计卡片 -->
    <NCard title="采集统计" :bordered="false" class="card-wrapper">
      <NGrid :cols="4" :x-gap="16">
        <NGridItem>
          <NStatistic label="总文件数" :value="statistics.totalFiles || 0" />
        </NGridItem>
        <NGridItem>
          <NStatistic label="总解析记录数" :value="statistics.totalParsedRecords || 0" />
        </NGridItem>
        <NGridItem>
          <NStatistic label="总入库记录数" :value="statistics.totalLoadedRecords || 0" />
        </NGridItem>
        <NGridItem>
          <NStatistic label="总文件大小" :value="formatFileSize(statistics.totalFileSize || 0)" />
        </NGridItem>
      </NGrid>
    </NCard>

    <!-- 查询表单 -->
    <NCard title="查询条件" :bordered="false" class="card-wrapper">
      <NSpace vertical>
        <NSpace>
          <NInput
            v-model:value="queryParams.fileName"
            placeholder="文件名"
            clearable
            style="width: 200px"
          />
          <NSelect
            v-model:value="queryParams.fileType"
            :options="fileTypeOptions"
            placeholder="文件类型"
            clearable
            style="width: 150px"
          />
          <NSelect
            v-model:value="queryParams.status"
            :options="statusOptions"
            placeholder="状态"
            clearable
            style="width: 150px"
          />
          <NDatePicker
            v-model:value="queryParams.startTime"
            type="datetime"
            placeholder="开始时间"
            clearable
            style="width: 200px"
          />
          <NDatePicker
            v-model:value="queryParams.endTime"
            type="datetime"
            placeholder="结束时间"
            clearable
            style="width: 200px"
          />
        </NSpace>
        <NSpace>
          <NButton type="primary" @click="handleSearch">
            <template #icon>
              <icon-ic-round-search />
            </template>
            搜索
          </NButton>
          <NButton @click="handleReset">
            <template #icon>
              <icon-ic-round-refresh />
            </template>
            重置
          </NButton>
        </NSpace>
      </NSpace>
    </NCard>

    <!-- 数据表格 -->
    <NCard title="文件记录" :bordered="false" class="card-wrapper flex-1-hidden">
      <NDataTable
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :scroll-x="1200"
        :pagination="{
          page: queryParams.pageNum,
          pageSize: queryParams.pageSize,
          itemCount: total,
          showSizePicker: true,
          pageSizes: [10, 20, 50, 100],
          onUpdatePage: handlePageChange,
          onUpdatePageSize: handlePageSizeChange
        }"
        flex-height
        class="flex-1-hidden"
      />
    </NCard>

    <!-- 详情抽屉 -->
    <NDrawer v-model:show="detailDrawerVisible" :width="600" title="文件记录详情">
      <NCard v-if="currentRecord" :bordered="false">
        <NDescriptions :column="1" label-placement="left">
          <NDescriptionsItem label="文件名">{{ currentRecord.fileName }}</NDescriptionsItem>
          <NDescriptionsItem label="文件类型">{{ currentRecord.fileType }}</NDescriptionsItem>
          <NDescriptionsItem label="文件大小">{{ formatFileSize(currentRecord.fileSize) }}</NDescriptionsItem>
          <NDescriptionsItem label="文件MD5">{{ currentRecord.fileMd5 }}</NDescriptionsItem>
          <NDescriptionsItem label="状态">
            <NTag :type="currentRecord.status === 'SUCCESS' ? 'success' : 'error'">
              {{ currentRecord.status }}
            </NTag>
          </NDescriptionsItem>
          <NDescriptionsItem label="解析记录数">{{ currentRecord.parsedRecords }}</NDescriptionsItem>
          <NDescriptionsItem label="入库记录数">{{ currentRecord.loadedRecords }}</NDescriptionsItem>
          <NDescriptionsItem label="任务编码">{{ currentRecord.taskCode }}</NDescriptionsItem>
          <NDescriptionsItem label="规则名称">{{ currentRecord.ruleName }}</NDescriptionsItem>
          <NDescriptionsItem label="采集时间">{{ currentRecord.createTime }}</NDescriptionsItem>
          <NDescriptionsItem v-if="currentRecord.errorMessage" label="错误信息">
            <span class="text-red">{{ currentRecord.errorMessage }}</span>
          </NDescriptionsItem>
        </NDescriptions>
      </NCard>
    </NDrawer>

    <!-- 预览抽屉 -->
    <NDrawer v-model:show="previewDrawerVisible" :width="800" title="数据预览">
      <NCard v-if="previewData" :bordered="false">
        <NSpace vertical>
          <NDescriptions :column="2" label-placement="left">
            <NDescriptionsItem label="文件名">{{ previewData.fileName }}</NDescriptionsItem>
            <NDescriptionsItem label="文件类型">{{ previewData.fileType }}</NDescriptionsItem>
            <NDescriptionsItem label="总记录数">{{ previewData.totalRecords }}</NDescriptionsItem>
            <NDescriptionsItem label="预览记录数">{{ previewData.previewRecords }}</NDescriptionsItem>
          </NDescriptions>
          <NDataTable
            :columns="previewData.data && previewData.data.length > 0 ? Object.keys(previewData.data[0]).map(key => ({ title: key, key })) : []"
            :data="previewData.data || []"
            :max-height="500"
            :scroll-x="800"
          />
        </NSpace>
      </NCard>
    </NDrawer>
  </div>
</template>

<style scoped>
.card-wrapper {
  box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
}
</style>
